﻿using DotnetCore.Extension.DependencyInjection;
using MQTT.Share.MQTT.Message;
using MQTTnet;
using MQTTnet.Server;
using System;

namespace MQTT.Server.MqttHandler
{
    public class MessageHandler : ITransientDependency
    {

        private IMqttServer MqttServer { get; set; }

        public void SetServer(IMqttServer mqttServer)
        {
            MqttServer = mqttServer;
        }

        public void Handle(MqttMessage mqttMessage)
        {
            if (MqttServer == null)
            {
                throw new Exception("MqttServer没有初始化");
            }

            string clientTopicTarget = "client";
            string serverTopicTarget = "server";
            if (mqttMessage.Topic.StartsWith(clientTopicTarget))
            {
                string toTopic = serverTopicTarget + mqttMessage.Topic.Substring(clientTopicTarget.Length);
                var message = new MqttApplicationMessageBuilder()
                    .WithTopic(toTopic)
                    .WithPayload(mqttMessage.Body)
                    .WithExactlyOnceQoS()
                    .WithRetainFlag(false)
                    .Build();
                MqttServer.PublishAsync(message);
            }
        }
    }
}
